package com.wz.project.system.employee.controller;

import com.wz.common.utils.StringUtils;
import com.wz.framework.aspectj.lang.annotation.Log;
import com.wz.framework.aspectj.lang.enums.BusinessType;
import com.wz.framework.web.controller.BaseController;
import com.wz.framework.web.domain.AjaxResult;
import com.wz.framework.web.page.TableDataInfo;
import com.wz.project.system.dept.domain.Dept;
import com.wz.project.system.dept.service.IDeptService;
import com.wz.project.system.employee.domain.Employee;
import com.wz.project.system.employee.domain.EmployeeVO;
import com.wz.project.system.employee.mapper.EmployeeMapper;
import com.wz.project.system.employee.mapper.EmployeeVoMapper;
import com.wz.project.system.employee.service.EmployeeService;
import com.wz.project.system.post.service.IPostService;
import com.wz.project.system.role.service.IRoleService;
import com.wz.project.system.user.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


@RestController
@RequestMapping("system/employee")
public class EmployeeController extends BaseController {

    private static final String prefix = "system/employee";

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployeeVoMapper employeeVoMapper;

    @Autowired
    private IDeptService deptService;
    @Autowired
    private IPostService postService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private EmployeeMapper employeeMapper;


    @GetMapping("test")
    public Object getEmployee(Integer prjgroupId){
        List<Employee> employees = employeeService.selectEmployeeListByPrjgroup(prjgroupId);
        return employees;
    }


    @GetMapping()
    public ModelAndView employee(){
        return new ModelAndView(prefix+"/employee");
    }

    /**
     * 批量为员工添加账号
     * @return
     */
    @PostMapping("batchOpenAcc")
    public Object batchOpenAccount(String ids){
        return employeeService.batchOpenAccountForEmployee(ids);
    }

    /**
     * 跳转添加用户界面
     * @return
     */
    @GetMapping("toUser/{employeeId}")
    public ModelAndView empToUser(@PathVariable Integer employeeId,ModelMap mmap){
        //查询员工并封装用户实体
        EmployeeVO employeeVO = employeeService.selectEmployeeById(employeeId);
        User user = initUser(employeeVO);
        mmap.put("user",user);
        mmap.put("roles", roleService.selectRoleAll().stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostAll());
        return new ModelAndView("system/user/add");
    }

    private User initUser(EmployeeVO employeeVO) {
        User user = new User();
        user.setDelFlag(User.DEL_FLAG);
        user.setDept(new Dept(){{
            setDeptId(Long.valueOf(employeeVO.getDeptId()));
            setDeptName(employeeVO.getDeptName());
        }});
        user.setLoginName(employeeVO.getEmpNo());
        user.setPhonenumber(employeeVO.getMobile());
        return user;
    }


//    @RequiresPermissions("system:employee:list")
    @PostMapping("/list")
    public Object list(Employee Employee){
        //单表查询可以用分页插件，多表最好不要用
        startPage();
        if (!StringUtils.isNull(Employee.getDeptId())){
            if (Employee.getDeptId() == 12 || Employee.getDeptId() == 1 || Employee.getDeptId() == 2){
                Employee.setDeptId(null);
            }
        }
//        List<Employee> employees = employeeService.selectEmployeeList(Employee);
        List<EmployeeVO> employees = employeeVoMapper.selectEmployeeList(Employee);//这个方法底层用了多表查询
        TableDataInfo dataTable = getDataTable(employees);
        //封装部门信息
//        return combineDept(dataTable);
        return dataTable;
    }


    private Object combineDept(TableDataInfo dataTable) {
        List<Dept> depts = deptService.selectDeptList(new Dept());
        Map<Long, Dept> collect = depts.stream().collect(Collectors.toMap(Dept::getDeptId, Function.identity()));
        List<EmployeeVO> employeeVOS = new ArrayList<>();
        for (Employee item : (List<Employee>) dataTable.getRows()) {
            EmployeeVO employeeVO = new EmployeeVO();
            BeanUtils.copyProperties(item,employeeVO);
            employeeVO.setDeptName(collect.get(Long.valueOf(employeeVO.getDeptId())).getDeptName());
            employeeVOS.add(employeeVO);
        }
        dataTable.setRows(employeeVOS);
        return dataTable;
    }


    @PostMapping("employeeStatusList")
    @ResponseBody
    public Object employeeStatusListForMain(Employee employee){
        TableDataInfo dataTable = getDataTable(employeeService.selectEmployeeList(employee));
        return combineDept(dataTable);

    }


    /**
     * 新增员工
     */
    @GetMapping("/add")
    public ModelAndView add(ModelMap mmap) {
        mmap.put("posts", postService.selectPostAll());
        return new ModelAndView(prefix + "/add");
    }

    /**
     * 新增保存员工
     */
    @RequiresPermissions("system:employee:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave( Employee Employee) {
        return toAjax(employeeService.insertEmployee(Employee));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{employeeId}")
    public ModelAndView edit(@PathVariable("employeeId") Integer EmployeeId, ModelMap mmap)
    {
        mmap.put("employee", employeeService.selectEmployeeById(EmployeeId));
        mmap.put("posts", postService.selectPostsByEmployeeId(EmployeeId));
        return new ModelAndView(prefix + "/edit");
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:employee:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated Employee Employee)
    {
        return toAjax(employeeService.updateEmployee(Employee));
    }

    @RequiresPermissions("system:employee:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(employeeService.deleteEmployeeByIds(ids));
    }

    /**
     * 验证手机号是否重复
     * @param phonenumber
     * @return
     */
    @PostMapping("/checkPhoneUnique")
    public Object CheckPhoneUnique(String phonenumber){
        Employee employee = new Employee();
        employee.setMobile(phonenumber);
        List<Employee> employees = employeeService.selectEmployeeList(employee);

        return employees.size();
    }

    /**
     * 验证员工号是否重复
     * @param empNo
     * @return
     */
    @PostMapping("/checkEmpNoUnique")
    public Object CheckEmpNoUnique(String empNo){
        Employee employee = new Employee();
        employee.setEmpNo(empNo);
        List<Employee> employees = employeeService.selectEmployeeList(employee);
        return employees.size();
    }

    /**
     * 获取当前员工所属项目组
     */
    @PostMapping("/findPrjNameByEmpId")
    public List<String> findPrjNameByEmpId(Integer employeeId){
        List<String> prjNames = employeeVoMapper.selectPrjNameByEmpId(employeeId);
        return prjNames;
    }
}
